<template>
  <a-modal
    :title="mdlStatus == 'add' ? '上传APP' : '修改'"
    :width="720"
    :visible="visible"
    :confirmLoading="loading"
    @ok="ok"
    @cancel="
      () => {
        $emit('cancel')
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <!-- <a-form-item label="描述">
          <a-input v-decorator="['description', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item> -->
        <a-form-item label="APP名称">
          <a-input
            placeholder="请输入"
            v-decorator="['name', { rules: [{ required: true, message: '请输入APP名称' }] }]"
          />
        </a-form-item>
        <a-form-item label="更新内容">
          <a-textarea
            :rows="4"
            placeholder="请输入"
            v-decorator="['content', { rules: [{ required: false, message: '请输入更新内容' }] }]"
          />
        </a-form-item>
        <a-form-item label="APK">
          <div style="display: flex">
            <a-input
              disabled
              style="flex: 0 0 1; background: none; border: none; color: #000000b4"
              placeholder="请选择文件"
              v-decorator="['packageName', { rules: [{ required: true, message: '请选择APK上传' }] }]"
            />
            <a-upload
              style="display: flex; flex-direction: column"
              v-decorator="['apk']"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :remove="handleRemove"
              accept=".apk"
              @change="parseApk"
              v-show="showUpBtn"
            >
              <a-button style="flex-shrink: 0; margin-left: 10px" type="primary">上传</a-button>
            </a-upload>
            <a-icon type="delete" theme="filled" style="display: flex; align-items: center" @click="handleRemoveDel" v-show="!showUpBtn" />
          </div>
        </a-form-item>
        <a-row>
          <a-col :span="8" :offset="2">
            <a-form-item label="图标" :labelCol="{ sm: { span: 6 } }" :wrapperCol="{ sm: { span: 6 } }">
              <a-upload
                name="avatar"
                list-type="picture-card"
                :show-upload-list="false"
                v-decorator="['iconUrl', { rules: [{ required: true, message: '请选择' }] }]"
                :before-upload="beforeUpload"
                :remove="handleRemoveIcon"
                @change="changeIcon"
              >
                <div class="icon-wrapper">
                  <div v-if="!form.getFieldValue('iconUrl')">
                    <a-icon type="plus" />
                    <div>上传照片</div>
                  </div>
                  <div v-else class="icon-hover">
                    <div>重新选择</div>
                  </div>
                  <img class="block-img" :src="form.getFieldValue('iconUrl')" alt="" />
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="14">
            <a-form-item label="版本名称" :labelCol="{ sm: { span: 6 } }" :wrapperCol="{ sm: { span: 15 } }">
              <a-input
                placeholder="请输入"
                v-decorator="['versionName', { rules: [{ required: true, message: '请输入版本名称' }] }]"
              />
            </a-form-item>
            <a-form-item label="版本号" :labelCol="{ sm: { span: 6 } }" :wrapperCol="{ sm: { span: 15 } }">
              <a-input
                placeholder="请输入"
                v-decorator="['version', { rules: [{ required: true, message: '请输入版本号' }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="平台">
          <a-input :value="tagName" disabled />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { fileToBase64, imageUrlToBase64 } from '@/utils/file'

export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    mdlStatus: {
      type: String,
      default: () => 'add'
    },
    tagName: {
      type: String,
      default: () => ''
    },
    tagId: {
      type: Number,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
    return {
      form: this.$form.createForm(this),
      fileList: [],
      showUpBtn: true
    }
  },
  watch: {
    visible: {
      handler (val) {
        // this.$form.resetFields()
        if (!val) return
        this.$nextTick(() => {
          this.form.resetFields()
          this.showUpBtn = true
        })
      },
      deep: true
    },
    model: {
      handler (val) {
        if (!val?.id) return
        this.$nextTick(async () => {
          const iconUrl = await imageUrlToBase64(val.iconUrl)
          this.form.setFieldsValue({
            iconUrl,
            name: val.name,
            content: val.content,
            versionName: val.versionName,
            version: val.version,
            packageName: val.packageName,
            id: val.id
          })
          this.showUpBtn = false
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    showUploadIcon () {
      return !!this.form.getFieldValue('iconUrl')
    },
    showUploadBtn () {
      this.showUpBtn = !this.form.getFieldValue('packageName')
    },
    beforeUpload () {
      return false
    },
    handleRemoveDel () {
      this.form.setFieldsValue({
        packageName: '',
        name: '',
        content: '',
        iconUrl: '',
        version: ''
      })
      this.fileList = []
      this.showUpBtn = true
    },
    handleRemove () {
      this.form.setFieldsValue({
        packageName: ''
      })
      this.fileList = []
    },
    handleRemoveIcon () {
      this.form.setFieldsValue({
        iconUrl: ''
      })
    },
    async changeIcon (e) {
      const { file, fileList = [] } = e
      if (!fileList.length) {
        this.form.setFieldsValue({
          iconUrl: ''
        })
        return
      }
      const iconUrl = await fileToBase64(file)
      this.form.setFieldsValue({
        iconUrl
      })
    },
    async parseApk ({ file, fileList = [] }) {
      if (!fileList.length) {
        return
      }
      try {
        const parser = new window.AppInfoParser(file)
        const { versionName, icon, package: packageNames } = await parser.parse()
        this.showUpBtn = false
        this.form.setFieldsValue({
          name: file.name,
          iconUrl: icon,
          packageName: packageNames,
          version: versionName
        })
      } catch (error) {
        this.$message.error('文件错误')
      }
    },
    ok () {
      try {
        const model = this.model
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            this.$emit('ok', {
              ...model,
              ...values
            })
          }
        })
      } catch (error) {}
    }
  }
}
</script>
<style lang="less" scoped>
.block-img {
  display: block;
  width: 100%;
  height: auto;
}
.icon-hover {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
  background-color: rgba(#000, 0.55);
  transition: 0.25s linear;
  color: #ffffff;
  text-align: center;
  border-radius: 4px;
  &:hover {
    opacity: 1;
  }
}
.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
  width: 100%;
  height: 100%;
}
</style>
